package net.apps123.soundmeter;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import net.apps123.commonaclasses.MyBaseClass;
import net.apps123.mqtt.MQClient;
import net.apps123.utils.IpUtils;
import net.apps123.view.SplAdapter;
import net.apps123.view.SplDataBean;
import net.apps123.view.SplView;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class HunXiangActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks,
        EasyPermissions.RationaleCallbacks {

    HashMap<String, short[]> deviceList = new HashMap<>();

    static private MyClassHunXiang myClass = null;
    private static final int PERMISSION_CAMERA = 1000; //权限的请求码唯一即可
    String[] perms = {Manifest.permission.RECORD_AUDIO, Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE}; //一些权限用逗号隔

    public static MqttClient mqttClient;
    //端口号
    private  final int MQTT_PORT = 1883; // Broker Port
    //服务ip
    private  final String MQTT_BROKER = "150.158.41.159"; // Broker URL or IP Address
    //连接地址
    private  final String MQTT_URL_FORMAT = "tcp://%s:%d"; // URL Format normally don't change
    //用户id
    private  final String CLINET_ID = "setApp";// client id
    //主题订阅
    private  final String TOPIC = "WH-HFS-R";// a topic

    private Button startBtn;

    public static MqttClient getMqttClient(){
        if (mqttClient != null){
            return mqttClient;
        }
        return null;
    }


    private Context mContext;
    private SplView splView;
    private ListView remoteSplList;
    private List<SplDataBean> splList = new ArrayList<>();
    private SplAdapter splAdapter ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hunxiang2);

        findViewById(R.id.genBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(MainActivity.this, SignalGenActivity.class));
                playWav( v);
            }
        });

        findViewById(R.id.backImg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.ResultBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HunXiangActivity.this, HunXiangDetailActivity.class));
            }
        });

        //
        initRemoteDevice();

        startBtn = findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mqttClient.publish("setApp", "start".getBytes(), 1, false);
//                            playWav( v);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        findViewById(R.id.remoteBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HunXiangActivity.this, RemoteActivity.class));
            }
        });

        if (myClass != null)
            myClass.InitViews(this);

        myClass = MyClassHunXiang.Instance(this);
        myClass.fs = myClass.onFastSlow(MyBaseClass.FastSlow.Slow);
//		findViewById(R.id.textView21).performClick();
        doSomethingWithCamera();

        /**创建一个url*/
        String url = String.format(Locale.US, MQTT_URL_FORMAT, MQTT_BROKER, MQTT_PORT);
        /**创建一个MQClient*/
        try {
            MemoryPersistence mMemStore = new MemoryPersistence(); // On Fail reverts to MemoryStore
            mqttClient = new MQClient(url, CLINET_ID+ System.currentTimeMillis(), mMemStore);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName("spl");
            options.setPassword("spl".toCharArray());
            mqttClient.connect();
            mqttClient.subscribe("setApp", 0);
            mqttClient.setTimeToWait(10 * 60 * 1000);
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    Log.d("=====", "====connectionLost");
                    Toast.makeText(HunXiangActivity.this, "===connectionLost==", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    Log.d("=====", "====messageArrived" );
                    String mqttContent =  new String(mqttMessage.getPayload());
//                    Log.d("====", mqttContent.length() + "====" + mqttContent);

                    if (!s.equals("setApp") ){
                        return;
                    }
                    String cmdStr = mqttContent.substring(0, 5);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try{
                                if (cmdStr.contains("start")){
//									startBtn.performClick();
                                    myClass.on_off = myClass.onOn_Off(myClass.on_off);
//                                    startBtn.setText("开始");
                                }else if (cmdStr.contains("stop")){
//									startBtn.performClick();
                                    myClass.on_off = myClass.onOn_Off(myClass.on_off);
//                                    startBtn.setText("结束");
                                }else {
                                    Log.d("==data==", "数据来了");
                                    Intent intent = new Intent("com.gasFragment");
                                    byte[] revData = new byte[mqttMessage.getPayload().length - 4];
                                    System.arraycopy(mqttMessage.getPayload(), 4, revData, 0, mqttMessage.getPayload().length - 4);
                                    intent.putExtra("data", revData);

                                    byte[] ipByte =   new byte[4];
                                    System.arraycopy(mqttMessage.getPayload(), 0, ipByte, 0, 4);
                                    InetAddress inetAddress = InetAddress.getByAddress(ipByte);
                                    String ipStr = inetAddress.getHostAddress();

                                    intent.putExtra("ipStr", ipStr);
                                    sendBroadcast(intent);
                                    updateRemoteDevice(intent);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    });
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    Log.d("=====", "=====deliveryComplete");
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }

         String[] starArray = {"控制端","被控制端"};
        //声明一个下拉列表的数组适配器
        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>(this, R.layout.item_select, starArray);
        //设置数组适配器的布局样式
//        starAdapter.setDropDownViewResource(R.layout.item_dropdown);
        //从布局文件中获取名叫sp_dialog的下拉框
        Spinner sp = findViewById(R.id.controlSpinner);
        //设置下拉框的标题，不设置就没有难看的标题了
        sp.setPrompt("请选择行星");
        //设置下拉框的数组适配器
        sp.setAdapter(starAdapter);
        //设置下拉框默认的显示第一项
        sp.setSelection(0);
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0){
                    startBtn.setVisibility(View.VISIBLE);
                }else{
                    startBtn.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //重置数据
    public void onReset(View view) {
        myClass.onReset();
    }

    //暂停
    public void onPC(View view) {
        myClass.onPause();
    }

    //fft 倍频程切换
    public void onSwap(View view) {
        myClass.selection = myClass.onSwap(myClass.selection);
    }

    //开始继续
    public void onOn_Off(View view) {
        if (EasyPermissions.hasPermissions(this, perms)) {
            //当前有权限时进行的操作
            if (myClass != null)
                myClass.InitViews(this);

            myClass = MyClassHunXiang.Instance(this);
            myClass.fs = myClass.onFastSlow(MyBaseClass.FastSlow.Slow);
            myClass.on_off = myClass.onOn_Off(myClass.on_off);
        } else {
            //没有权限去申请权限
            EasyPermissions.requestPermissions(
                    this, "该权限仅是实现音频分析，请通过权限否则不能使用某些功能！", PERMISSION_CAMERA, perms);
        }

    }

    //快慢切换
    public void onFastSlow(View view) {
        myClass.fs = myClass.onFastSlow(myClass.fs);
    }

    //平均算法
    public void onMLN(View view) {
        myClass.mln = myClass.onMLN(myClass.mln);
    }

    @Override
    public void onPermissionsGranted(int i, @NonNull List<String> list) {
        Toast.makeText(this, "应用获得权限成功", Toast.LENGTH_LONG).show();
        String ipStr = IpUtils.getWifiIPAddress(HunXiangActivity.this);
        Log.d("====", "ipStr==" + ipStr);
    }

    @Override
    public void onPermissionsDenied(int i, @NonNull List<String> list) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, Arrays.asList(perms))) {
            //在权限弹窗中，用户勾选了'不在提示'且拒绝权限的情况触发
            new AppSettingsDialog.Builder(this).build().show(); //调用接口进入该应用的设置页面
        }

    }

    @Override
    public void onRationaleAccepted(int i) {

    }

    @Override
    public void onRationaleDenied(int i) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 回调结果传递给EasyPermission
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

    }

    /**
     * 权限请求方法可直接调用
     */
    @AfterPermissionGranted(PERMISSION_CAMERA)
    public void doSomethingWithCamera() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            //当前有权限时进行的操作
            if (myClass != null)
                myClass.InitViews(this);

            myClass = MyClassHunXiang.Instance(this);
            myClass.fs = myClass.onFastSlow(MyBaseClass.FastSlow.Slow);

            String ipStr = IpUtils.getWifiIPAddress(HunXiangActivity.this);
            Log.d("====", "ipStr==" + ipStr);

        } else {
            //没有权限去申请权限
            EasyPermissions.requestPermissions(
                    this, "该权限仅是实现音频分析，请通过权限否则不能使用某些功能！", PERMISSION_CAMERA, perms);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            Toast.makeText(this, "音频权限为" + EasyPermissions.hasPermissions(this,
                    perms), Toast.LENGTH_LONG).show();
        }
    }


    private MediaPlayer mediaPlayer;
    private void playWav( View  view) {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(getBaseContext(), Uri.parse("android.resource://"
                    + getBaseContext().getPackageName() + "/" + R.raw.whie_noise_10s_48k));
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }

        if (mqttClient != null){
            try {
                mqttClient.disconnect();
                mqttClient.close();;
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    private void initRemoteDevice(){
        splView = findViewById(R.id.splView);
        remoteSplList = findViewById(R.id.remoteSplList);
        splList = new ArrayList<>();
        splAdapter = new SplAdapter(this, splList);
        remoteSplList.setAdapter(splAdapter);
    }

    private void updateRemoteDevice(Intent intent){
        byte[] dataArr = intent.getExtras().getByteArray("data");
        Log.d("=======", "ReceiveBroadCast==" + dataArr.length);
        String ipStr = intent.getStringExtra("ipStr");
        if (dataArr == null || dataArr.length < 1278){
            return;
        }
        short [] buffer = new short[dataArr.length / 2];
        ByteBuffer.wrap(dataArr).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(buffer);

        deviceList.put(ipStr, buffer);
        if (splView != null){
            splView.updateView(buffer, "");
        }

        splList.clear();

        Set<String> keySet = deviceList.keySet();
        for (String key : keySet) {
            System.out.println("key:" + key + " , value:" );
            SplDataBean splDataBean = new SplDataBean(key, deviceList.get(key));
            splList.add(splDataBean);
        }
        splAdapter.notifyDataSetChanged();

    }
}
